//
//  UserDetailsViewController.swift
//  puretennis
//
//  Created by Derek Zheng on 12/5/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit
import CoreLocation

class UserDetailsViewController: UIViewController, WebSocketDelegate, UITextFieldDelegate {

    var guid: String!
    
    var userDetails: NSMutableDictionary?

    var userImage: UIImageView = UIImageView()

    var nickname: UILabel = UILabel()
    
    var distanceLabel: UILabel = UILabel()
    
    var playYearLabel: UILabel = UILabel()
    
    var messageView = UITextField()
    
    var socket:WebSocket?

    var messageListView: ChatMessageTableView!

    override func viewDidLoad() {
        self.initNavigation();
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        GlobalVariables.currentUserDetails = self
    }
    
    override func viewWillAppear(animated: Bool) {
        self.hideTabBar()

        ViewUtils.addBackgroundView(self)
        self.navigationItem.titleView = ViewUtils.titleView("好友信息")
        self.addWebSocket()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        self.view = nil
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalVariables.currentUserDetails = nil
        self.removeWebSocket()
    }
    
    func addWebSocket(){
        //In personal chat, the identifier is the message receiver.
        
        var currentUserGuid = Utils.getValue("guid") as String
        
        var path = "/message/chat?friendGuid=\(self.guid)&currentUserGuid=\(currentUserGuid)"
        
        socket = WebSocket(url: NSURL(scheme: "ws", host: Properties.WEBSOKET_HOST, path: path)!)
        socket?.delegate = self
        socket?.connect()
    }
    
    func removeWebSocket(){
        socket?.disconnect()
        socket = nil
    }
    
    func websocketDidConnect() {
        Utils.debug("Websocket \(self.guid) is connected")
    }
    
    func websocketDidDisconnect(error: NSError?) {
        if let e = error {
            Utils.debug("websocket \(self.guid) is disconnected: \(e.localizedDescription)")
        }
    }
    
    func websocketDidWriteError(error: NSError?) {
        if let e = error {
            Utils.debug("wez got an error from the websocket \(self.guid): \(e.localizedDescription)")
        }
    }
    
    func websocketDidReceiveMessage(text: String) {
        var message = Utils.jsonToNSDictionary(text)
        self.messageListView.addMessage(message!)
    }
    
    func websocketDidReceiveData(data: NSData) {

    }
    
    
    func initNavigation(){
        var backButton = UIButton();
        backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.showsTouchWhenHighlighted = true;
        backButton.sizeToFit();
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        var backBarItem = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarItem;
    }
    
    // Back
    func back(sender:UIButton){
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    func loadUserDetailsViews(){
        
        self.initFriendActionButton()
        

        userImage.image = ImageUtils.retrieveUserImage(self.guid, reload: true)

        var height = (self.navigationController?.navigationBar.frame.height)! + ViewUtils.statusBarHeight()
        
        let imageMargin: CGFloat = 5
        userImage.frame.origin.x = imageMargin
        userImage.frame.origin.y = (self.navigationController?.navigationBar.frame.height)! + ViewUtils.statusBarHeight() + imageMargin;
        var userImageWidth = self.view.frame.width * 0.4;
        userImage.frame.size = CGSize(width: userImageWidth, height: userImageWidth);
        userImage.layer.masksToBounds = true;
        userImage.layer.cornerRadius = 4;
        self.view.addSubview(userImage);

        nickname.text = self.userDetails!.objectForKey("nickname") as? String

        nickname.frame.origin.x = userImage.frame.width + 10 + imageMargin;
        nickname.frame.origin.y = userImage.frame.origin.y + imageMargin;
        
        nickname.font = Utils.fontHupo(16);
        nickname.textColor = UIColor.whiteColor()
        nickname.sizeToFit()

        self.view.addSubview(nickname)
        
        let gender = self.userDetails?.objectForKey("gender") as String
        var genderImageName = "male"
        
        if("FEMALE" == gender){
            genderImageName = "female"
        }
        
        
        var genderImage = UIImageView(image: UIImage(named: genderImageName))
        genderImage.frame.size = CGSize(width: 16, height: 16)
        genderImage.frame.origin.x = nickname.frame.origin.x + nickname.frame.width
        genderImage.frame.origin.y = nickname.frame.origin.y - 5
        self.view.addSubview(genderImage)
        
        
        var playYear = self.userDetails?.objectForKey("playYear") as NSDictionary
        let playYearText = playYear.objectForKey("playYear") as String
        playYearLabel.text = "球龄\(playYearText)"
        playYearLabel.frame.origin.x = nickname.frame.origin.x
        playYearLabel.frame.origin.y = nickname.frame.origin.y + 30;
        playYearLabel.font = Utils.fontHupo(14)
        playYearLabel.textColor = UIColor.whiteColor()
        playYearLabel.sizeToFit()
        self.view.addSubview(playYearLabel)
        
        var location = self.userDetails!.objectForKey("location") as NSDictionary
        
        var myLocationCache: AnyObject? = Utils.getValue("currentLocation")
        
        if(myLocationCache != nil){

            
            var myLocation = myLocationCache as NSDictionary
            
            var userLocationObj = LocationManager.toLocation(location);
            var myLocationObj = LocationManager.toLocation(myLocation);
            var distance:CLLocationDistance = myLocationObj.distanceFromLocation(userLocationObj)
            
            var lastupdate = location.objectForKey("lastupdate") as String
            var distanceLabelText = ""
            if(!lastupdate.isEmpty){
                
                var locationIcon = UIImageView(image: UIImage(named: "location"))
                locationIcon.frame.size = CGSize(width: 16, height: 16)
                locationIcon.frame.origin.x = playYearLabel.frame.origin.x
                locationIcon.frame.origin.y = playYearLabel.frame.origin.y + 30;
                self.view.addSubview(locationIcon)
                
                var lastupdateLabel = DateUtils.intervalToNowText(lastupdate)
                distanceLabelText = "\(LocationManager.toDistanceText(distance)) \(lastupdateLabel)前"
                
                distanceLabel.text = distanceLabelText
                
                distanceLabel.frame.origin.x = locationIcon.frame.origin.x + 20
                distanceLabel.frame.origin.y = playYearLabel.frame.origin.y + 30;
                distanceLabel.font = Utils.fontHupo(14);
                distanceLabel.textColor = UIColor.whiteColor()
                distanceLabel.sizeToFit()
                
                self.view.addSubview(distanceLabel)

            }
        }
        
        var isFriend = self.userDetails!.objectForKey("friend") as Bool
        
        if(isFriend){
            messageView.delegate = self
            messageView.returnKeyType = UIReturnKeyType.Send
            messageView.placeholder = "跟小伙伴说点什么..."
            messageView.borderStyle = UITextBorderStyle.RoundedRect
            messageView.backgroundColor = UIColor.whiteColor()
            messageView.frame.origin.x = userImage.frame.origin.x
            messageView.frame.origin.y = userImage.frame.origin.y + userImage.frame.height + 5
            messageView.frame.size = CGSize(width: self.view.frame.width * 0.95, height: 35)
            self.view.addSubview(messageView)
            
            self.messageListView = ChatMessageTableView(identifier: "\(self.guid)")
            
            self.messageListView.backgroundColor = UIColor.clearColor()
            self.messageListView.frame.origin.x = messageView.frame.origin.x
            self.messageListView.frame.origin.y = messageView.frame.origin.y + messageView.frame.height + 5            
            self.messageListView.frame.size = CGSize(width: self.view.frame.width * 0.95, height: (self.view.frame.height - self.messageListView.frame.origin.y))
            self.messageListView.retrieveDataFromLocalStorage()
            self.view.addSubview(self.messageListView)
            

        }
        
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool{
         // called when 'return' key pressed. return NO to ignore.
        self.sendMessage()
        textField.resignFirstResponder()
        return true
    }
    
    
    func sendMessage(){
        var text = self.messageView.text
        
        if(text.isEmpty){
            return
        }
        var url = "/api/v1/chat/send"
        var body = NSMutableDictionary()
        body.setValue(false, forKey: "group")
        body.setValue(self.guid, forKey: "guid")
        body.setValue(text, forKey: "message")

        
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: body, successHandle: { (response) -> Void in
            var message = response as NSMutableDictionary
            self.messageListView.addMessage(message)
            self.messageView.text = ""
            
        }, errorHandle: { (error) -> Void in
            
        })
        
    }
    
    func sendAddFriendRequest(addFriendRequestButton: UIButton){
        self.processComplete();
        var url = "/api/v1/friends/request"
        var body = NSMutableDictionary()
        body.setObject(self.guid, forKey: "guid")
        
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: body, successHandle: { (response) -> Void in

            UIAlertView(title: "发送请求", message: "好友请求已经发送！", delegate: self, cancelButtonTitle: "知道了").show();
            self.processComplete();
            self.back(addFriendRequestButton)
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
    
    
    func acceptAddFriendRequest(acceptFriendRequestButton: UIButton){

        var url = "/api/v1/friends/request/accept/" + self.guid;
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            self.back(acceptFriendRequestButton)
            }, errorHandle: { (error) -> Void in
                
        })
    }
    
    func deleteFriend(acceptFriendRequestButton: UIButton){
        ConfirmView(message: "确定删除此小伙伴?", confirm: { () -> Void in

            var url = "/api/v1/friends/delete/" + self.guid;
            HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
                self.back(acceptFriendRequestButton)
                }, errorHandle: { (error) -> Void in
                    
            });
            }, cancel: nil).show();
    }
    
    func initFriendActionButton(){
        
        var isFriend = self.userDetails!.objectForKey("friend") as Bool
        var bgImageName: String!
        var actionMethodName: String!
        
        if(!isFriend){
            var friendRequested = self.userDetails!.objectForKey("friendRequested") as Bool
            if(friendRequested){
                bgImageName = "confirm"
                actionMethodName = "acceptAddFriendRequest:"
            }else{
                bgImageName = "add"
                actionMethodName = "sendAddFriendRequest:"
            }
        }else{
            bgImageName = "close"
            actionMethodName = "deleteFriend:"
        }

        
        let addFriendButton = UIButton();
        addFriendButton.setImage(UIImage(named: bgImageName), forState: UIControlState.Normal);
        addFriendButton.contentMode = UIViewContentMode.Right;
        addFriendButton.showsTouchWhenHighlighted = true;
        addFriendButton.sizeToFit();
        addFriendButton.addTarget(self, action: Selector(actionMethodName), forControlEvents: UIControlEvents.TouchUpInside);
        let addFriendItem = UIBarButtonItem(customView: addFriendButton);
        self.navigationItem.rightBarButtonItems = [addFriendItem];
    }
    
    func loadUserDetails() {
        self.processing();
        var url = "/api/v1/user/"+guid;
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var details = response as NSMutableDictionary;
            self.userDetails = details
            self.loadUserDetailsViews();
            self.processComplete();
            }, errorHandle: { (error) -> Void in
                self.processComplete();
        });
    }
}
